<template>
  <div class="pet-detail-container" v-loading="loading">
    <el-card class="main-card" v-if="petInfo">
      <div class="back-link">
        <el-link icon="ArrowLeft" @click="goBack">返回宠物列表</el-link>
      </div>

      <!-- 宠物基本信息 -->
      <div class="pet-info-section">
        <div class="pet-image">
          <el-image
            :src="petInfo.coverImage || ''"
            fit="cover"
            style="width: 100%; height: 100%"
          ></el-image>
        </div>
        <div class="pet-info">
          <h1 class="pet-name">
            {{ petInfo.recipeName }}
            <el-tag
              :type="
                petInfo.status === '1'
                  ? 'warning'
                  : petInfo.status === '2'
                  ? 'info'
                  : 'success'
              "
              class="status-tag"
            >
              {{
                petInfo.status === "1"
                  ? "待领养"
                  : petInfo.status === "2"
                  ? "已确定领养"
                  : "已领养"
              }}
            </el-tag>
          </h1>
          <div class="pet-meta">
            <p>
              <strong>分类：</strong>
              {{ getCategoryName(petInfo.categoryId) }}
            </p>
            <p>
              <strong>年龄：</strong>
              {{ petInfo.age }} 岁
            </p>
            <p>
              <strong>性别：</strong>
              {{
                petInfo.gender === 1
                  ? "公"
                  : petInfo.gender === 2
                  ? "母"
                  : "未知"
              }}
            </p>
            <p>
              <strong>发布时间：</strong>
              {{ formatDate(petInfo.createTime) }}
            </p>
            <p>
              <strong>发布人：</strong>
              {{ petInfo.createBy }}
            </p>
          </div>
          <div class="pet-description">
            <strong>宠物描述：</strong>
            <p>{{ petInfo.description }}</p>
          </div>
          <div class="pet-actions" v-if="petInfo.status === '1'">
            <el-button type="primary" @click="handleAdopt" :disabled="!isLogin">
              {{ isLogin ? "申请领养" : "请先登录" }}
            </el-button>
          </div>
        </div>
      </div>

      <!-- Tab栏切换详细内容和评论 -->
      <div class="tab-section">
        <el-tabs v-model="activeTab">
          <el-tab-pane label="宠物详情" name="detail">
            <div
              class="pet-content"
              v-html="petInfo.petContent || petInfo.description"
            ></div>
          </el-tab-pane>
          <el-tab-pane label="评论区" name="comments">
            <!-- 发表评论 -->
            <div class="comment-form">
              <el-input
                v-model="commentForm.content"
                type="textarea"
                :rows="3"
                placeholder="请输入您的评论..."
                :disabled="!isLogin"
              ></el-input>
              <div class="form-actions">
                <el-button
                  type="primary"
                  @click="submitComment"
                  :disabled="!isLogin"
                >
                  {{ isLogin ? "发表评论" : "请先登录" }}
                </el-button>
              </div>
            </div>

            <!-- 评论列表 -->
            <div class="comment-list">
              <div v-if="comments.length === 0" class="no-comments">
                暂无评论，快来发表第一条评论吧！
              </div>
              <div
                v-else
                class="comment-item"
                v-for="comment in comments"
                :key="comment.commentId"
              >
                <div class="comment-header">
                  <div class="user-info">
                    <el-avatar :size="40" :src="comment.avatar"></el-avatar>
                    <div class="user-meta">
                      <span class="username">{{ comment.createBy }}</span>
                      <span class="comment-time">{{
                        formatDate(comment.createTime)
                      }}</span>
                    </div>
                  </div>
                </div>
                <div class="comment-content">{{ comment.content }}</div>
              </div>
            </div>

            <!-- 评论分页 -->
            <div class="comment-pagination" v-if="comments.length > 0">
              <el-pagination
                background
                layout="prev, pager, next"
                :total="commentTotal"
                :page-size="commentQuery.pageSize"
                :current-page="commentQuery.pageNum"
                @current-change="handleCommentPageChange"
              />
            </div>
          </el-tab-pane>
        </el-tabs>
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from "vue";
import { useRouter, useRoute } from "vue-router";
import { ElMessage, ElMessageBox } from "element-plus";
import { getRecipe, applyAdoption } from "@/api/recipe";
import { getRecipeComments, addComment } from "@/api/recipe";
import { treeCategory } from "@/api/category";
import { getToken } from "@/utils/auth";

const router = useRouter();
const route = useRoute();

const id = route.params.id; // 宠物ID
const loading = ref(true);
const petInfo = ref(null);
const categoryOptions = ref([]);
const activeTab = ref("detail");

// 评论相关
const comments = ref([]);
const commentTotal = ref(0);
const commentQuery = reactive({
  pageNum: 1,
  pageSize: 10,
});
const commentForm = reactive({
  content: "",
  recipeId: id,
});

// 是否已登录
const isLogin = computed(() => {
  return !!getToken() || localStorage.getItem("isLogin") === "true";
});

// 获取宠物详情
const getPetDetail = async () => {
  loading.value = true;
  try {
    const res = await getRecipe(id);
    if (res.code === 200 && res.data) {
      petInfo.value = res.data;
    } else {
      // 接口调用失败，使用模拟数据
      useMockPetData();
    }
  } catch (error) {
    console.error("获取宠物详情失败:", error);
    useMockPetData();
  } finally {
    loading.value = false;
  }
};

// 使用模拟宠物数据
const useMockPetData = () => {
  petInfo.value = {
    recipeId: id,
    recipeName: "可爱的小猫咪",
    categoryId: 1,
    coverImage:
      "https://img0.baidu.com/it/u=1394778073,2898249422&fm=253&fmt=auto&app=138&f=JPEG?w=500&h=333",
    age: 2,
    gender: 1,
    status: "1",
    createTime: new Date().toISOString(),
    createBy: "管理员",
    description:
      "这是一只非常可爱的小猫，它非常友好，适合家庭饲养。它喜欢与人互动，也很容易照顾。如果你正在寻找一个忠实的伴侣，不要错过这个机会！",
    petContent: `
      <h3>宠物详情</h3>
      <p>名称：可爱的小猫咪</p>
      <p>品种：英短</p>
      <p>性格：活泼、友善、亲人</p>
      <p>饲养要求：</p>
      <ul>
        <li>定期接种疫苗</li>
        <li>提供干净的饮水和食物</li>
        <li>定期梳理毛发</li>
        <li>提供猫砂盆和玩具</li>
      </ul>
      <p>领养须知：领养是一项长期的承诺，请确保您有足够的时间和精力照顾这只宠物。</p>
    `,
  };
};

// 获取分类数据
const getCategoryData = async () => {
  try {
    const res = await treeCategory();
    if (res.code === 200 && res.data) {
      categoryOptions.value = res.data;
    } else {
      // 接口调用失败，使用默认数据
      useMockCategoryData();
    }
  } catch (error) {
    console.error("获取分类数据失败:", error);
    useMockCategoryData();
  }
};

// 使用模拟分类数据
const useMockCategoryData = () => {
  categoryOptions.value = [
    {
      categoryId: 1,
      categoryName: "猫咪",
      children: [
        { categoryId: 4, categoryName: "英短" },
        { categoryId: 5, categoryName: "加菲" },
        { categoryId: 6, categoryName: "暹罗" },
      ],
    },
    {
      categoryId: 2,
      categoryName: "狗狗",
      children: [
        { categoryId: 7, categoryName: "金毛" },
        { categoryId: 8, categoryName: "哈士奇" },
        { categoryId: 9, categoryName: "泰迪" },
      ],
    },
    {
      categoryId: 3,
      categoryName: "其他宠物",
      children: [
        { categoryId: 10, categoryName: "兔子" },
        { categoryId: 11, categoryName: "仓鼠" },
      ],
    },
  ];
};

// 获取评论数据
const getComments = async () => {
  try {
    const res = await getRecipeComments(id);
    if (res.code === 200 && res.rows) {
      comments.value = res.rows;
      commentTotal.value = res.total || res.rows.length;
    } else {
      // 接口调用失败，使用模拟数据
      useMockCommentData();
    }
  } catch (error) {
    console.error("获取评论数据失败:", error);
    useMockCommentData();
  }
};

// 使用模拟评论数据
const useMockCommentData = () => {
  const mockComments = [];
  for (let i = 0; i < 5; i++) {
    mockComments.push({
      commentId: i + 1,
      recipeId: id,
      content: `这是第${
        i + 1
      }条模拟评论，宠物看起来真不错！希望能有一个好主人！`,
      createTime: new Date(Date.now() - i * 86400000).toISOString(),
      createBy: `用户${i + 1}`,
      avatar: "",
    });
  }
  comments.value = mockComments;
  commentTotal.value = mockComments.length;
};

// 提交评论
const submitComment = async () => {
  if (!commentForm.content.trim()) {
    ElMessage.warning("评论内容不能为空");
    return;
  }

  if (!isLogin.value) {
    ElMessage.warning("请先登录后再评论");
    return;
  }

  try {
    // 获取用户ID并确保它是数字类型
    const userId = parseInt(localStorage.getItem("userId") || "1", 10);
    const userName = localStorage.getItem("username") || "当前用户";

    const res = await addComment({
      recipeId: id,
      content: commentForm.content,
      userId: userId,
      userName: userName,
    });

    if (res.code === 200) {
      ElMessage.success("评论发表成功");
      commentForm.content = ""; // 清空评论内容
      await getComments(); // 重新获取评论列表
    } else {
      ElMessage.error(res.msg || "评论发表失败");
    }
  } catch (error) {
    console.error("提交评论失败:", error);
    ElMessage.error("评论发表失败，请重试");

    // 模拟添加评论成功
    const newComment = {
      commentId: new Date().getTime(),
      recipeId: id,
      content: commentForm.content,
      createTime: new Date().toISOString(),
      createBy: localStorage.getItem("username") || "当前用户",
      avatar: "",
    };
    comments.value.unshift(newComment);
    commentTotal.value += 1;
    commentForm.content = "";
    ElMessage.success("(模拟)评论发表成功");
  }
};

// 评论分页变化
const handleCommentPageChange = (page) => {
  commentQuery.pageNum = page;
  getComments();
};

// 根据分类ID获取分类名称
const getCategoryName = (categoryId) => {
  // 使用递归函数在分类树中查找指定ID的分类
  function findCategory(categories, id) {
    for (const category of categories) {
      if (category.categoryId == id) {
        return category;
      }
      if (category.children && category.children.length > 0) {
        const found = findCategory(category.children, id);
        if (found) return found;
      }
    }
    return null;
  }

  const category = findCategory(categoryOptions.value, categoryId);
  return category ? category.categoryName : categoryId;
};

// 处理领养申请
const handleAdopt = () => {
  if (!isLogin.value) {
    ElMessageBox.confirm("需要登录才能申请领养，是否前往登录？", "提示", {
      confirmButtonText: "前往登录",
      cancelButtonText: "取消",
      type: "warning",
    }).then(() => {
      router.push(`/login?redirect=/pet/detail/${id}`);
    });
    return;
  }

  // 直接弹出确认窗口，不再显示表单
  ElMessageBox.confirm("确认要申请领养这只宠物吗？", "领养确认", {
    confirmButtonText: "确认领养",
    cancelButtonText: "取消",
    type: "info",
  })
    .then(() => {
      submitAdoptRequest();
    })
    .catch(() => {
      // 用户取消，不做任何处理
    });
};

// 提交领养请求
const submitAdoptRequest = async () => {
  try {
    // 调用API提交领养申请
    const res = await applyAdoption({
      recipeId: id,
    });

    if (res.code === 200) {
      ElMessage.success("领养申请提交成功");

      // 刷新宠物信息
      await getPetDetail();

      // 提示用户后续流程
      ElMessageBox.alert(
        "您的领养申请已提交成功！工作人员将会尽快与您联系确认详情。",
        "申请成功",
        {
          confirmButtonText: "知道了",
          type: "success",
        }
      );
    } else {
      ElMessage.error(res.msg || "领养申请提交失败");
    }
  } catch (error) {
    console.error("提交领养申请失败:", error);

    // 模拟领养成功
    ElMessage.success("(模拟)领养申请提交成功");

    // 更新宠物状态
    if (petInfo.value) {
      petInfo.value.status = "2";
    }

    // 提示用户后续流程
    ElMessageBox.alert(
      "（模拟）您的领养申请已提交成功！工作人员将会尽快与您联系确认详情。",
      "申请成功",
      {
        confirmButtonText: "知道了",
        type: "success",
      }
    );
  }
};

// 格式化日期
const formatDate = (dateStr) => {
  if (!dateStr) return "";
  const date = new Date(dateStr);
  return date.toLocaleDateString("zh-CN", {
    year: "numeric",
    month: "2-digit",
    day: "2-digit",
    hour: "2-digit",
    minute: "2-digit",
  });
};

// 返回上一页
const goBack = () => {
  router.back();
};

onMounted(async () => {
  await getCategoryData();
  await getPetDetail();
  await getComments();
});
</script>

<style scoped>
.pet-detail-container {
  max-width: 1000px;
  margin: 0 auto;
  padding: 20px;
}

.main-card {
  margin-bottom: 30px;
}

.back-link {
  margin-bottom: 20px;
}

.pet-info-section {
  display: flex;
  flex-wrap: wrap;
  gap: 30px;
  margin-bottom: 30px;
}

.pet-image {
  flex: 1;
  min-width: 300px;
  max-width: 350px;
  height: 280px;
  border-radius: 8px;
  overflow: hidden;
  background-color: #f5f7fa;
}

.pet-info {
  flex: 2;
  min-width: 300px;
}

.pet-name {
  margin-top: 0;
  margin-bottom: 20px;
  display: flex;
  align-items: center;
}

.status-tag {
  margin-left: 10px;
}

.pet-meta {
  margin-bottom: 20px;
}

.pet-meta p {
  margin: 8px 0;
}

.pet-description {
  margin-bottom: 20px;
}

.pet-description p {
  margin-top: 8px;
  line-height: 1.6;
}

.pet-actions {
  margin-top: 20px;
}

.tab-section {
  margin-top: 30px;
}

.pet-content {
  padding: 20px 0;
  line-height: 1.6;
}

.comment-form {
  margin-bottom: 30px;
}

.form-actions {
  margin-top: 10px;
  text-align: right;
}

.comment-list {
  margin-bottom: 20px;
}

.no-comments {
  text-align: center;
  padding: 20px;
  color: #909399;
}

.comment-item {
  padding: 15px 0;
  border-bottom: 1px solid #ebeef5;
}

.comment-header {
  margin-bottom: 10px;
}

.user-info {
  display: flex;
  align-items: center;
}

.user-meta {
  margin-left: 10px;
}

.username {
  font-weight: 500;
  margin-right: 10px;
}

.comment-time {
  font-size: 12px;
  color: #909399;
}

.comment-content {
  line-height: 1.6;
  padding: 0 0 0 50px;
}

.comment-pagination {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}

@media (max-width: 768px) {
  .pet-info-section {
    flex-direction: column;
  }

  .pet-image,
  .pet-info {
    max-width: 100%;
  }
}
</style>
